package org.example.spring_boot_blog.common.utils;

import lombok.val;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class SecurityUtil {
    public static String encrypt(String password){
        if(!StringUtils.hasLength(password)){
            throw new RuntimeException("密码不能为空");
        }
        String salt= UUID.randomUUID().toString().replace("-","");
//        salt+password
        String securityPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        return salt+securityPassword;
    }
    public static boolean verify(String inputPassword,String sqlPassword) {
            if(!StringUtils.hasLength(inputPassword)||!StringUtils.hasLength(sqlPassword)){
                return false;
            }
            if(sqlPassword.length()!=64){
                return false;
            }
            String salt=sqlPassword.substring(0,32);
            String securityPassword = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes(StandardCharsets.UTF_8));
            return sqlPassword.equals(salt+securityPassword);
    }
}
